/*
Copyright (c) 2008  Franklin Schmidt <fschmidt@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package fschmidt.db.base;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Properties;
import fschmidt.db.DbObject;
import fschmidt.db.DbKey;
import fschmidt.db.DbKeySetter;
import fschmidt.db.DbObjectFactory;
import fschmidt.db.SQLRuntimeException;
import fschmidt.db.LongKey;
import fschmidt.db.StringKey;
import fschmidt.db.DbStorable;
import fschmidt.db.extend.DbRecordExt;
import fschmidt.db.extend.DbDatabaseExt;
import fschmidt.db.extend.DbTableExt;
import fschmidt.db.extend.DbTransaction;


public abstract class DbDatabaseImpl extends DbDatabaseExt {
	private final String url;
	private final Properties props = new Properties();

	public DbDatabaseImpl(String url,String user,String password) {
		this.url = url;
		props.setProperty("user",user);
		props.setProperty("password",password);
	}

	public void setProperty(String key,String value) {
		props.setProperty(key,value);
	}

	public Properties getProperties() {
		return props;
	}

	public Connection getConnection()
		throws SQLException
	{
		return DriverManager.getConnection(url,props);
	}

	public <K extends DbKey,V extends DbObject<K,V>> DbTableExt<K,V> newTable(DbDatabaseExt database,String tableName,DbKeySetter<K> keySetter,DbObjectFactory<K,V> objectFactory) {
		return new DbTableImpl<K,V>(database,tableName,keySetter,objectFactory);
	}

	public <K extends DbKey,V extends DbObject<K,V>> DbRecordExt<K,V> newRecord(DbTableExt<K,V> table,V obj,K key) {
		return new DbRecordImpl<K,V>(table,obj,key);
	}

	public <K extends DbKey,V extends DbObject<K,V>> DbRecordExt<K,V> newRecord(DbTableExt<K,V> table,V obj) {
		return new DbRecordImpl<K,V>(table,obj);
	}

	public boolean isInTransaction() {
		throw new UnsupportedOperationException();
	}

	public void beginTransaction()
		throws SQLRuntimeException
	{
		throw new UnsupportedOperationException();
	}

	public void commitTransaction()
		throws SQLRuntimeException
	{
		throw new UnsupportedOperationException();
	}

	public void endTransaction()
		throws SQLRuntimeException
	{
		throw new UnsupportedOperationException();
	}

	public void runBeforeCommit(Runnable r) {
		r.run();
	}

	public void runAfterCommit(Runnable r) {
		r.run();
	}

	public DbTransaction getTransaction() {
		return null;
	}

	public void ignoreRunnablesInThisTransaction() {
		throw new UnsupportedOperationException();
	}


	public DbKeySetter<LongKey> newIdentityLongKeySetter(String fieldName) {
		return new LongKeySetter(fieldName);
	}

	public DbKeySetter<LongKey> newAssignedLongKeySetter(String fieldName) {
		return new LongForeignKeySetter(fieldName);
	}

	public DbKeySetter<StringKey> newAssignedStringKeySetter(String fieldName) {
		return new StringKeySetter(fieldName);
	}

	public void setValue(PreparedStatement stmt,int idx,Object value)
		throws SQLException
	{
		if( value==null ) {
			throw new SQLException("null value");
		} else if( value instanceof DbStorable ) {
			((DbStorable)value).setField(stmt,idx);
		} else if( value instanceof Character ) {
			stmt.setString(idx,value.toString());
		} else if( value instanceof java.util.Date ) {
			stmt.setTimestamp(idx,new java.sql.Timestamp(((java.util.Date)value).getTime()));
		} else if( (new byte[0]).getClass().isInstance(value) ) {
			stmt.setBytes(idx,(byte[])value);
		} else if( value instanceof Boolean ) {
			stmt.setBoolean( idx, ((Boolean)value).booleanValue() );
		} else if( value instanceof Float ) {
			stmt.setFloat( idx, ((Float)value).floatValue() );
		} else {
			stmt.setObject(idx,value);
		}
	}




	public String quote(String s) {
		return "'" + stringEncode(s) + "'";
	}

	public String stringEncode(String s) {
		StringBuilder buf = new StringBuilder();
		int n = s.length();
		for( int i=0; i<n; i++ ) {
			char c = s.charAt(i);
			switch(c) {
				case '\n': 
					buf.append("\\n");
					break;
				case '\t':
					buf.append("\\t");
					break;
				case '\r':
					buf.append("\\r");
					break;
				case '\'':
					buf.append("\\'");
					break;
				default:
					buf.append(c);
			}
		}
		return buf.toString();
	}

	private static final DateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public String quote(java.util.Date date) {
		return "'" + stringEncode(date) + "'";
	}

	public String stringEncode(java.util.Date date) {
		return dateFmt.format(date);
	}

}
